package com.tz.pay.marlon.core.service;


import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.JDOMException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.tz.pay.marlon.core.utils.CommonUtilPub;
import com.tz.pay.marlon.core.utils.ConfigUtil;
import com.tz.pay.marlon.core.utils.PayCommonUtil;
import com.tz.util.jdomXMLUtil;

 @Controller
public class CmsDonationxxAct {

	/**
	 * 微信支付信息
	 * @param request
	 * @param jkje(捐款金额)
	 * @return
	 */
//	@RequestMapping(value = "/donationxx/v_wxzf.do",produces="application/json")
//	@ResponseBody
//	public String wxzf(HttpServletRequest request,HttpServletResponse response,double jkje,String id) {
//		JSONObject object = new JSONObject();
//    	//参数
//    	String product_id=String.valueOf("JZ"+UtilDate.getDate()+System.currentTimeMillis());//订单id，自动生成
//    	BigDecimal numberOfMoney = new BigDecimal(jkje);
//    	String body=NumberToCN.number2CNMontrayUnit(numberOfMoney);//描述
//    	Integer tota = (int)(jkje * 100);
//    	String totalFee=tota.toString();//金额必须为整数  单位为分
//    	String codeurl = PaymentAct.getcodeUrl(product_id,body,totalFee);
//    	//String path="D:";
//    	String path = request.getSession().getServletContext()
//				.getRealPath("/");
//    	String picPath=paymentAct.getQrurl(path,codeurl,product_id);
//    	System.out.println("product_id=="+product_id);
    	
//    	if(picPath!=null)
//    	{
//    		Donationxx donationxx =	cmsDonationMng.findById(id);
//    		donationxx.setJzh(product_id);
//    		cmsDonationMng.update(donationxx);
//    		picPath =product_id +".png";
//    	}else{
//    		picPath ="1";//图片生成未成功
//    		object.put("ms", picPath) ;
//    		ResponseUtils.renderJson(response, object.toString());
//    	}
//		return picPath;
//	}
	/**
	 * 支付是否成功
	 * @param request
	 * @param 
	 * @return
	 */
	@RequestMapping(value = "/donationxx/v_zfsfcg.do" , method = RequestMethod.POST, produces="application/json")
	@ResponseBody
	public void zfsfcg(HttpServletRequest request,HttpServletResponse response,String id,String product_id) {
		PaymentAct paymentAct= new PaymentAct();
		JSONObject object = new JSONObject();
		String flag = "";
		Map<String, String> map=new HashMap<String, String>();
    	//String zfxx=paymentAct.queryOrder("1461039561909");
    	String zfxx=paymentAct.queryOrder(product_id);
    	try {
			map = jdomXMLUtil.doXMLParse(zfxx);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	String returnCode = map.get("return_code");
        String resultCode = map.get("result_code");
        String trade_state_desc = map.get("trade_state_desc");
        String cash_fee = map.get("cash_fee");
//        Donationxx donationxx =	cmsDonationMng.findById(id);
//        if(returnCode.equalsIgnoreCase("SUCCESS")&&resultCode.equalsIgnoreCase("SUCCESS")){
//	        if(cash_fee!=null&&!"".equals(cash_fee))
//	        {
//	        	donationxx.setStates(1);//支付完成
//	        	double  dzje  =  Double.parseDouble(cash_fee); 
//	        	double tota = (dzje / 100);
//	        	donationxx.setDzje(tota);
//	        	donationxx.setZfsj(new Date());
//	        	flag =  "1";//支付成功
//	        	System.out.println("cash_fee=="+cash_fee);
//	        }else if(trade_state_desc!=null&&!"".equals(trade_state_desc)){
//	        	donationxx.setStates(2);//支付未完成
//	        	donationxx.setZfsj(new Date());
//	        	System.out.println("trade_state_desc=="+trade_state_desc);
//	        	flag =  "2";//支付未成功
//	        }
//        }else{
//        	donationxx.setStates(3);//支付异常
//        	donationxx.setZfsj(new Date());
//        	flag =  "3";//支付异常
//        }
//        cmsDonationMng.update(donationxx);
//        object.put("ms", flag) ;
//		ResponseUtils.renderJson(response, object.toString());
	}


    /**
     * 统一支付初始化数据
     * 
     * 
     */
    public String initXmlData(String openid,String totalFee,String body){
    	HashMap<String, String> paramMap = new HashMap<String, String>();
    	String attach="gaobo24man";
    	
    	String product_id=String.valueOf(System.currentTimeMillis());
    	
    	paramMap.put("appid", ConfigUtil.APPID); //appid
    	paramMap.put("mch_id", ConfigUtil.MCH_ID); //商户号
    	paramMap.put("nonce_str", PayCommonUtil.CreateNoncestr());  //随机数
    	paramMap.put("body", body);         //描述
    	paramMap.put("attach", attach);  
    	paramMap.put("out_trade_no", product_id); //商户 后台的贸易单号

    	paramMap.put("total_fee", totalFee); //金额必须为整数  单位为分
    	paramMap.put("spbill_create_ip",localIp()); //本机的Ip
    	paramMap.put("notify_url", "http://www.baidu.com"); //支付成功后，回调地址     
    	paramMap.put("trade_type", "JSAPI"); //交易类型
    	paramMap.put("openid", openid); //交易类型
    	
    	paramMap.put("sign", PayCommonUtil.createSignJSAPI("UTF-8", paramMap,ConfigUtil.API_KEY));//根据微信签名规则，生成签名
    	
    	String xmlData = CommonUtilPub.mapToXml(paramMap);//把参数转换成XML数据格式
    	System.out.println("xmlData=="+xmlData);
    	return xmlData;
    }
    
	private String localIp(){
		String ip = null;
		Enumeration allNetInterfaces;
				try {
					allNetInterfaces = NetworkInterface.getNetworkInterfaces();            
					while (allNetInterfaces.hasMoreElements()) {
						NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
						List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
						for (InterfaceAddress add : InterfaceAddress) {
							InetAddress Ip = add.getAddress();
							if (Ip != null && Ip instanceof Inet4Address) {
								ip = Ip.getHostAddress();
							}
						}
					}
				} catch (SocketException e) {
					e.printStackTrace();
				}
			return ip;
		}
}
